package li.nibble.twittertido;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import li.nibble.twittertido.beans.Tweet;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;

public abstract class Utils {

	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException ioe) {
			Log.e("convertStreamToString()", ioe.getLocalizedMessage());
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				Log.e("convertStreamToString() - finally",
						e.getLocalizedMessage());
			}
		}
		return sb.toString();
	}

	public static Timestamp convertStringToTimestamp(String date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date date_d;
		try {
			date_d = sdf.parse(date);
			return new Timestamp(date_d.getTime());
		} catch (ParseException e) {
			return new Timestamp(new Date().getTime());
		}
	}

	public static InputStream fetch(String urlString) {
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet request = new HttpGet(urlString);
		HttpResponse response;
		try {
			response = httpClient.execute(request);
			return response.getEntity().getContent();
		} catch (ClientProtocolException e) {
			Log.e("Utils.fetch", e.getLocalizedMessage());
		} catch (IOException e) {
			Log.e("Utils.fetch", e.getLocalizedMessage());
		}
		return null;
	}

	public static boolean isEmail(String correo) {
		Pattern pat = null;
		Matcher mat = null;
		pat = Pattern
				.compile("^([0-9a-zA-Z]([_.w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+([a-zA-Z]{2,9}.)+[a-zA-Z]{2,3})$");
		mat = pat.matcher(correo);
		if (mat.find()) {
			return true;
		} else {
			return false;
		}
	}

	public static boolean isTextValid(String text) {
		Pattern pattern;
		Matcher matcher;
		String USERNAME_PATTERN = "^[a-z0-9_-]{4,15}$";
		pattern = Pattern.compile(USERNAME_PATTERN);
		matcher = pattern.matcher(text);
		return matcher.matches();
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	public static boolean isOnline(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		try {
			return cm.getActiveNetworkInfo().isConnectedOrConnecting();
		} catch (Exception e) {
			return false;
		}
	}

	public static Tweet getTweet(String id) {
		Tweet tweet = new Tweet();
		JSONObject j;
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet("http://api.twitter.com/1/statuses/show/"
				+ id + ".json");
		HttpResponse response;
		try {
			response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				j = new JSONObject(convertStreamToString(entity.getContent()));
				boolean forbidden = true;
				try {
					j.getString("error");
				} catch (Exception e) {
					forbidden = false;
				}

				if (!forbidden) {
					tweet.setTweet(j.getString("text"));
					tweet.setDate(j.getString("created_at"));
					JSONObject user = j.getJSONObject("user");
					tweet.setUser(user.getString("screen_name"));
					try {
						JSONObject retweet_status = j
								.getJSONObject("retweeted_status");
						if (retweet_status != null) {
							String id_2 = retweet_status.getString("id_str");
							if (id.compareToIgnoreCase(id_2) != 0) {
								return getTweet(id_2);
							}
						}

					} catch (JSONException e) {
						Log.e("Utils.getTweet() JSONException",
								e.getLocalizedMessage());
					}
				}else{
					return null;
				}
			}
		} catch (Exception e) {
			Log.e("Utils.getTweet() Exception", e.getLocalizedMessage());
			return null;
		}

		return tweet;
	}
}
